/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/store/';
import router from '@/router/router'
import {serialize} from '@/util/util'
import {getToken} from '@/util/auth'
import console from '@/util/console'
import {Message} from 'element-ui'
import website from '@/config/website';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {Base64} from 'js-base64';
import {Encrypt,Decrypt} from '@/util/cryptoJs'
import {encodeMd5} from '@/util/toolUtil'
import {setStore, getStore} from '@/util/store'
import errCode from '@/config/errorCode'


axios.defaults.timeout = 10000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
  showSpinner: false
});
//HTTPrequest拦截
axios.interceptors.request.use(config => {
  if(store.getters.timeOutFlag){
    return false;
  }
  checkPermission();
  NProgress.start() // start progress bar
  const meta = (config.meta || {});
  const isToken = meta.isToken;
  //过滤远程搜索无效请求
  if(config.method == 'get' && config.url.indexOf('{{key}}') > 0){
    config.url =  config.url.replace('{{key}}','')
  }
  if(config.method == 'get' && config.url.indexOf('columnValue=&') > 0){
    return Promise.reject(error);
  }
  console.log('=<< 开始请求，地址：'+config.url + ' 请求数据：', config.data)

  //处理报文体
  if (config.method === 'post' && meta.isSerialize === true) {
    config.data = serialize(config.data);
  }
  if(config.method === 'post' && website.isHttpEncode && config.url.indexOf('/file/upload') < 0){
    config.data = Encrypt(JSON.stringify(config.data));
  }
  //config.headers['Content-type'] = 'application/json;charset=UTF-8';
  console.log('config.url==',config.url);
  config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
  if ((getToken() && !isToken) || website.noCheckToken.indexOf(config.url) > -1) {
    if(config.method === 'post' && website.isHttpEncode){
      config.headers['UserSign'] = encodeMd5(config.data);
    }
    else
    {
      config.headers['UserSign'] = encodeMd5(config.data ? JSON.stringify(config.data) : '');
    }
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    //上传文件过滤处理
    if(config.url.indexOf('/file/upload') >= 0){
      config.headers['Content-Type'] = 'multipart/form-data';
      config.headers['UserSign'] = 'uploadFile';
    }
    config.headers['UserId'] = store.getters.userInfo.userId;
    config.headers['TenantId'] = store.getters.userInfo.tenantId || localStorage.getItem('tenantId');
    config.headers['remote'] = 'no';
    if (website.noCheckToken.indexOf(config.url) == -1) {
      config.headers['Authorization'] = 'bearer ' + getToken() // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
    }
  }
  
  return config
}, error => {
  return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
  NProgress.done();
  let showToastTime = 3000;
  let showMessage =  store.getters.showToastMsg;
  if(website.isHttpEncode && res.config.url != '/dooleenApi/oauth/token') {
    try {
      res.data = JSON.parse(Decrypt(res.data));
    } catch (e) {
      console.log('解密错误，原文输出！');
    }
  }
  //打印日志
  console.log('=>> 开始返回，请求地址：'+res.config.url + ' 返回数据：', res.data)

  const status = res.status || 200
  const statusWhiteList = website.statusWhiteList || [];
  let message = '未知错误';
  //如果在白名单里则自行catch逻辑处理
  if (statusWhiteList.includes(status)) return Promise.reject(res);
  if(errCode['E'+status]){
    if(!showMessage){
      Message({
        message: errCode['E'+status],
        type: 'error',
        customClass:'zZindex'
      })
      showMessage = true;
      store.dispatch('setShowToastMsg',true);
      setTimeout(() => {
        store.dispatch('setShowToastMsg',false);
      }, showToastTime);
    }
    return Promise.reject(new Error(message))
  }
  else if (status === 500) {
    if(!showMessage){
      Message({
        message: '系统内部错误，请联系管理员',
        type: 'error',
        customClass:'zZindex'
      })
      showMessage = true;
      store.dispatch('setShowToastMsg',true);
      setTimeout(() => {
        store.dispatch('setShowToastMsg',false);
      }, showToastTime);
    }
    return Promise.reject(new Error(message))
  } 
  //如果是401则跳转到登录页面
  else if (status === 401) {
    if(res.data.error == 'invalid_token'){
      message ='无效的访问TOKEN，请重新登录！'
      if(res.data.error_description.indexOf('Access token expired') >= 0)
      {
        message ='访问令牌过期'
      } 
    }
    else if(res.data.error == 'unauthorized'){
      message ='访问拒绝'
    }
    else{
      message = res.data.error;
      if(!message){
        message = res.data.message;
      }
    }
    if(!showMessage){
      Message({
        message: message,
        type: 'error',
        customClass:'zZindex'
      })
      showMessage = true;
      store.dispatch('setShowToastMsg',true);
      setTimeout(() => {
        store.dispatch('setShowToastMsg',false);
      }, showToastTime);
    }
    store.dispatch('FedLogOut').then(() => {window.location.href = '/#/index'});
    return Promise.reject(new Error(message))
  }
  // 如果请求为非200否者默认统一处理
  // 处理400错误
  else if (status === 400) {
    if(res.data.message.indexOf('Invalid refresh token') >= 0){
      if(!showMessage){
        Message({
          message: '无效的访问TOKEN，请重新登录！',
          type: 'error',
          customClass:'zZindex'
        })
        showMessage = true;
        store.dispatch('setShowToastMsg',true);
        setTimeout(() => {
          store.dispatch('setShowToastMsg',false);
        }, showToastTime);
      }
      store.dispatch('FedLogOut').then(() => router.push({ path: '/index?tenantId=' + localStorage.getItem('tenantId') +'&v1'}));
      return Promise.reject(new Error(message))
    }
    else{
      if(!showMessage){
        Message({
          message: res.data.message,
          type: 'error',
          customClass:'zZindex'
        })
        showMessage = true;
        store.dispatch('setShowToastMsg',true);
        setTimeout(() => {
          store.dispatch('setShowToastMsg',false);
        }, showToastTime);
      }
      return Promise.reject(new Error(message))
    }
  }
  else if (status === 404) {
    if(!showMessage){
      Message({
        message: '接口资源未找到，请联系管理员',
        type: 'error',
        customClass:'zZindex'
      })
      showMessage = true;
      store.dispatch('setShowToastMsg',true);
      setTimeout(() => {
        store.dispatch('setShowToastMsg',false);
      }, showToastTime);
    }
    return Promise.reject(new Error(message))
  } 
  else if (status === 444) {
    if(!showMessage){
      Message({
        message: '数据签名错误',
        type: 'error',
        customClass:'zZindex'
      })
      showMessage = true;
      store.dispatch('setShowToastMsg',true);
      setTimeout(() => {
        store.dispatch('setShowToastMsg',false);
      }, showToastTime);
    }
    return Promise.reject(new Error(message))
  } 
  else if (status !== 200) {
    if(!showMessage){
      Message({
        message: message,
        type: 'error',
        customClass:'zZindex'
      })
      showMessage = true;
      store.dispatch('setShowToastMsg',true);
      setTimeout(() => {
        store.dispatch('setShowToastMsg',false);
      }, showToastTime);
    }
    return Promise.reject(new Error(message))
  } 
  // 处理业务返回错误
  else { 
    //console.log('heade====',res.data.head)
    if(res.data.head && res.data.head.respCode !== 'S0000')
    {
      message = res.data.head.respMsg;
      let errorMsg = '';
      let errorMsgKey = '';
      let msgType = 'error';
      for (var key in message)
      {
        errorMsgKey = key
        let errMsg = message[key].split(':');
        if(errMsg[0] == 'info' || errMsg[0] == 'warning' || errMsg[0] == 'error'){
          msgType = errMsg[0];
          errorMsg = errMsg[1];
        }
        else{
          errorMsg = errMsg[0];
        }
      }
      let i = 0;
      // console.log('message===>', message);
      // console.log('errorMsg===>', errorMsg);
      //在配置里的错误码不用吐司提示
      if(website.noShowToast.indexOf(errorMsgKey) == -1){
        if(!showMessage){
          Message({
            message: '{'+errorMsgKey+':'+errorMsg+'}',
            type: msgType,
            customClass:'zZindex'
          })
          showMessage = true;
          store.dispatch('setShowToastMsg',true);
          setTimeout(() => {
            store.dispatch('setShowToastMsg',false);
          }, showToastTime);
        }
        return Promise.reject(new Error(message))
      }
    }
  } 
  return JSON.parse(JSON.stringify(res).replace(/"true"/g, 'true').replace(/"false"/g, 'false'));
}, error => {
  NProgress.done();
  return Promise.reject(new Error(error));
})

export default axios;
// 下载excel
export function downloadExcel(params) {
  //console.log('params.body.params 11= ', params);
  NProgress.start() // start progress bar
  let downloadElement = document.createElement('a');
  let href = params.url+'?UserSign='+encodeMd5('')+'&UID='+Base64.encode(store.getters.userInfo.userId)+'&remote=excel&tenantId='+params.data.tenantId+'&projectId='+params.data.projectId+'&bizCode='+params.data.bizCode+'&formId='+params.data.formId+'&orders='+params.data.orders+'&condition='+params.data.condition+'&token='+getToken()
  downloadElement.href = href;
  document.body.appendChild(downloadElement);
  downloadElement.click(); //点击下载
  document.body.removeChild(downloadElement); //下载完成移除元素
  window.URL.revokeObjectURL(href); //释放掉对象
  NProgress.done();
}
// 检查权限是否被篡改
function checkPermission(){
  if(sessionStorage.getItem(store.getters.userInfo.userId+'privatePermission')){
    let permissionSign = encodeMd5(JSON.stringify(JSON.parse(sessionStorage.getItem(store.getters.userInfo.userId+'privatePermission')).data));
    if(sessionStorage.getItem(store.getters.userInfo.userId+'privatePermission') && JSON.parse(sessionStorage.getItem(store.getters.userInfo.userId+'privatePermission')).sign != permissionSign){
      let newPermissionSign =  encodeMd5(JSON.stringify(getStore({name: store.getters.userInfo.userId+'permission'})));
      let permission = getStore({name: store.getters.userInfo.userId+'permission'})
      let privatePermission = {
        data: permission,
        sign: newPermissionSign
      }
      sessionStorage.setItem(store.getters.userInfo.userId+'privatePermission',JSON.stringify(privatePermission));
    }
  }
}